import { defineStore } from "pinia";
import { ref } from "vue";
import { getSvgCaptcha, userLogin, userLogout } from "@/api/user";
import type { LoginForm } from "@/typings/api";
import { useRouter } from "vue-router";

export const useUserStore = defineStore(
  "user",
  () => {
    const router = useRouter();

    const captchaDomString = ref<string>("");
    const currentCaptchaId = ref<number>(0);
    const userId = ref<string | number>("");

    /** 获取验证码 */
    const getCaptcha = async () => {
      try {
        const {
          data: { captcha, captchaId },
        } = await getSvgCaptcha();
        captchaDomString.value = captcha;
        currentCaptchaId.value = captchaId;
      } catch (error: any) {
        window.$message.error(error?.message ?? error);
      }
    };

    const token = ref<string>("");
    /** 登录 */
    const login = async (loginForm: LoginForm) => {
      try {
        const { data } = await userLogin(loginForm);
        token.value = data.accessToken;
        userId.value = data.userId;
      } catch (error: any) {
        window.$message.error(error?.message ?? error);
      }
    };

    /** 退出登录 */
    const logout = async () => {
      const { success } = await userLogout();
      if (success) {
        router.replace("/login");
      }
    };

    return {
      captchaDomString,
      currentCaptchaId,
      token,
      userId,
      getCaptcha,
      login,
      logout,
    };
  },
  { persist: true }
);
